import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { timStore } from '../../../../store/tim'
import TIM from 'tim-wx-sdk-ws'
import { getEventParam } from '../../../../utils/utils'
import Tim from '../../../../model/tim'
// pages/conversation/compoents/conversation-window/conversation-window.js
Component({
	/**
	 * 组件的属性列表
	 */
	behaviors: [storeBindingsBehavior],
	properties: {
		targetUserId: String,
		service: Object,
	},

	/**
	 * 组件的初始数据
	 */
	data: { text: '', scrollHeight: 0 },
	storeBindings: {
		store: timStore,
		fields: ['messageList', 'intoView', 'isCompleted'],
		actions: [
			'getMessageList',
			'setTargetUserId',
			'scrollMessageList',
			'pushMessage',
		],
	},
	lifetimes: {
		async attached() {
			this._setNavigationBarTitle()
			this.setScrollHeight()
			this.setTargetUserId(this.data.targetUserId)
			await this.getMessageList()
			if (this.data.service) {
				const message = Tim.getInstance().createMessage(
					TIM.TYPES.MSG_CUSTOM,
					this.data.service,
					this.data.targetUserId,
					'link'
				)
				this.pushMessage(message)
			}
		},
	},
	/**
	 * 组件的方法列表
	 */
	methods: {
		handleSendLink(event) {
			const service = getEventParam(event, 'service')
			this.triggerEvent('sendmessage', {
				type: TIM.TYPES.MSG_CUSTOM,
				content: service,
			})
		},
		handleSelect(event) {
			const service = getEventParam(event, 'service')
			wx.navigateTo({
				url: `/pages/service-detail/service-detail?service_id=${service.id}`,
			})
		},
		async handleSendImage() {
			const chooseImage = await wx.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['alum', 'camera'],
			})
			this.triggerEvent('sendmessage', {
				type: TIM.TYPES.MSG_IMAGE,
				content: chooseImage,
			})
		},
		async setScrollHeight() {
			const systemInfo = await wx.getSystemInfo()
			const scrollHeight =
				systemInfo.windowHeight -
				(systemInfo.screenHeight - systemInfo.safeArea.bottom) -
				95
			this.setData({
				scrollHeight,
			})
		},
		handleInput(event) {
			this.data.text = getEventParam(event, 'value')
		},
		handleSend() {
			const text = this.data.text.trim()
			if (text === '') {
				return
			}
			this.triggerEvent('sendmessage', {
				type: TIM.TYPES.MSG_TEXT,
				content: text,
			})
			this.setData({
				text: '',
			})
		},
		handleScrolltoupper() {
			if (this.data.isCompleted) {
				return
			}
			wx.showLoading({
				title: '正在加载...',
				mask: true,
			})
			this.scrollMessageList()
			setTimeout(() => {
				wx.hideLoading()
			}, 1000)
		},
		async _setNavigationBarTitle() {
			const res = await Tim.getInstance().getUserProfile(
				this.data.targetUserId
			)

			wx.setNavigationBarTitle({
				title: res[0].nick || '强强到家',
			})
		},
	},
})
